﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
//
using PerceptiveMCAPI;
using PerceptiveMCAPI.Methods;
using PerceptiveMCAPI.Types;
using PerceptiveMCAPI.Types.Internal;

namespace PerceptiveMCAPI_Test
{
   public partial class TestCode : System.Web.UI.Page
   {
      private EnumValues.AccessType AccessType = MCAPISettings.default_AccessType;
      private EnumValues.OutputType OutputType = MCAPISettings.default_OutputType;
      private EnumValues.MethodType MethodType = MCAPISettings.default_MethodType;
      private bool EncodeRequest = MCAPISettings.default_EncodeRequest;
      private bool ValidateRequest = MCAPISettings.default_Validate;

      private string userid = "your_id";
      private string password = "your_pwd";
      //
      private string apikey { get; set; }
      public bool showRawRequest { get; set; }
      public bool showRawResponse { get; set; }
      //
      private List<ApiMethod> _methods = new List<ApiMethod>();
      private List<ApiMethod> methods
      {
         get
         {
            if ( ViewState["methods"] != null )
            {
               _methods = ViewState["methods"] as List<ApiMethod>;
            }
            return _methods;
         }
         set { ViewState.Add( "methods", value ); }
      }

      protected void Page_Load( object sender, EventArgs e )
      {
         if ( !Page.IsPostBack )
         {
            LoadApiMethods();
         }
         apikey = MCAPISettings.default_apikey;    // or a specific key

         showRawRequest = true;
         showRawResponse = false;
         //
      }
      // ===========================================================================

      protected void btnRun_Click( object sender, EventArgs e )
      {
         // -------------------------------------------------------
         if ( !string.IsNullOrEmpty( this.apikey ) )
         {
            SetupTest();
            TestMethod( ddlMethods.SelectedValue );
         }
      }
      protected void btnSettings_Click( object sender, EventArgs e )
      {
         SetupTest();
         test_settings();
      }

      //=================================================================================
      private void TestMethod( string method )
      {
         // ----------------------- try it
         try
         {
            switch ( method )
            {
               case "campaignCreate": test_campaignCreate(); break;
               //
               case "apikeys": test_apikeys(); break;
               case "lists": test_lists(); break;
               case "listAbuseReports": test_listAbuseReports(); break;
               case "listBatchSubscribe": test_listBatchSubscribe(); break;
               case "listMergeVarAdd": test_listMergeVarAdd(); break;
               case "campaignUpdate": test_campaignUpdate(); break;
               case "campaignStats": test_campaignStats(); break;
               case "campaignSegmentTest": test_campaignSegmentTest(); break;
               case "campaignEmailDomainPerformance": test_campaignEmailDomainPerformance(); break;
               case "campaignShareReport": test_campaignShareReport(); break;
               // =====================================================================================
               default:
                  throw new ApplicationException( "Method isn't set up for testing." );
            }
         }
         catch ( Exception ex )
         {
            if ( ex.InnerException != null )
               ex = ex.InnerException;

            List<Api_ValidatorMessage> msgs = new List<Api_ValidatorMessage>();
            Api_ValidatorMessage msg = new Api_ValidatorMessage();
            msg.MessageLevel = EnumValues.MessageLevel.Terminal;
            msg.MessageText = ex.Message + "<br />" + ex.StackTrace;
            msg.PropertyName = "--";
            msgs.Add( msg );
            show_errors1.Display( msgs );
         }
      }

      private void test_listMergeVarAdd()
      {
         string listid = "List-id";

         listMergeVarAddInput input = new listMergeVarAddInput( apikey, listid, "bomb", "To blow up" );
         input.api_Validate = false;
         input.api_AccessType = EnumValues.AccessType.Serial;
         input.api_OutputType = EnumValues.OutputType.JSON;
         input.parms.apikey = apikey;
         //
         listMergeVarAdd cmd = new listMergeVarAdd( input );
         listMergeVarAddOutput output = cmd.Execute();
         show_DefaultResponse1.Display( output.result );
         showResults( output.api_Request, output.api_Response,
            output.api_ErrorMessages, output.api_ValidatorMessages );

      }

      private void test_campaignCreate()
      {
         string listid = "List-id";

         campaignCreateInput input = new campaignCreateInput();
         input.parms.type = PerceptiveMCAPI.EnumValues.campaign_type.regular;
         input.api_Validate = false;
         input.api_AccessType = EnumValues.AccessType.XmlRpc;
         input.api_OutputType = EnumValues.OutputType.XmlRpc;
         input.parms.apikey = apikey;
         //
         campaignCreateOptions options = new campaignCreateOptions();
         options.title = "My Campaign";
         options.from_email = "info@domain.com";
         options.from_name = "Some Name";
         options.list_id = listid;
         options.subject = "My Subject";
         input.parms.options = options;
         //
         Dictionary<string, string> content = new Dictionary<string, string>();
         content.Add( "html", "<h1>heading</h1>" );
         content.Add( "text", "Lorem Ipsum" );
         input.parms.content = content;

         campaignCreate cmd = new campaignCreate( input );
         campaignCreateOutput output = cmd.Execute();
         show_DefaultResponse1.Display( output.result );
         showResults( output.api_Request, output.api_Response,
            output.api_ErrorMessages, output.api_ValidatorMessages );

      }

      private void test_listAbuseReports()
      {
         listAbuseReportsInput input = new listAbuseReportsInput();
      }
      //====================================================================================================

      private void test_campaignShareReport()
      {
         lblTestName.Text = "campaignShareReport";

         campaignShareReportInput input = new campaignShareReportInput();

         // **** access, output, and validate
         input.api_AccessType = EnumValues.AccessType.Serial;
         input.api_OutputType = EnumValues.OutputType.JSON;
         input.api_Validate = false;
         //
         input.parms.apikey = "apikey-us1";
         input.parms.cid = "your_campaign";
         input.parms.opts = new Dictionary<string, object>();
         input.parms.opts.Add( "header_type", MCAPISettings.default_campaignShareReport_header_type );
         input.parms.opts.Add( "header_data", MCAPISettings.default_campaignShareReport_header_data );
         input.parms.opts.Add( "secure", MCAPISettings.default_campaignShareReport_secure );
         input.parms.opts.Add( "css_url", MCAPISettings.default_campaignShareReport_css_url );
         // --------------------------------------
         // execution
         campaignShareReport cmd = new campaignShareReport( input );
         campaignShareReportOutput output = cmd.Execute();

         List<campaignShareReportResults> csr = new List<campaignShareReportResults>();
         csr.Add( output.result );
         gvOutput.DataSource = csr;
         gvOutput.DataBind();
         showResults( output.api_Request, output.api_Response,
            output.api_ErrorMessages, output.api_ValidatorMessages );
      }
      //====================================================================================================

      private void test_campaignUpdate()
      {
         lblTestName.Text = "campaignUpdate";

         campaignUpdateInput input = new campaignUpdateInput();
         input.parms.apikey = "your-apikey";
         // **** access, output, and validate
         input.api_AccessType = AccessType;
         input.api_OutputType = OutputType;
         // -------------------------------------- input parms
         input.parms.cid = "cid-value";
         input.parms.name = "content";
         string main_content = @"<h1 class='title'>Perceptive Note</h1><p class='copy'>We do integrations.</p><p class='copy'>...and MUCH more.</p>";
         Dictionary<string, string> value = new Dictionary<string, string>();
         value.Add( "html_main", main_content );
         input.parms.value = value;
         // --------------------------------------
         // execution
         campaignUpdate cmd = new campaignUpdate( input );
         campaignUpdateOutput output = cmd.Execute();

         // format output 
         show_DefaultResponse1.Display( output.result );
         showResults( output.api_Request, output.api_Response,
            output.api_ErrorMessages, output.api_ValidatorMessages );

      }
      //====================================================================================================
      private void test_settings()
      {
         lblTestName.Text = "settings";

         Dictionary<string, string> settings = MCAPISettings.ListAPISettings();
         gvOutput.DataSource = settings; gvOutput.DataBind();
      }
      //-------------------------------------------------------------------- 
      public void test_apikeys()
      {
         apikeysInput input = new apikeysInput( userid, password, false );
         lblTestName.Text = "apikeys";
         // -------------------------------------------------------
         // **** access, output, and validate 
         input.api_AccessType = AccessType;
         input.api_OutputType = OutputType;
         input.api_Validate = ValidateRequest;
         // -------------------------------------------------------
         apikeys cmd = new apikeys( input );
         apikeysOutput output = cmd.Execute();
         //
         List<string> result_ToString = new List<string>();
         foreach ( apikeysResults result in output.result )
         {
            result_ToString.Add( result.ToString() );
         }
         // format output 
         // --------------------------
         show_apikeys1.Display( output ); show_apikeys1.Visible = true;    // user control

         if ( input.api_AccessType == EnumValues.AccessType.XmlRpc )
         { output.api_Request = apiXmlRpcRequestDisplayFormat.FormatParms( output.inputParms ); }

         showResults( output.api_Request, output.api_Response,
               output.api_ErrorMessages, output.api_ValidatorMessages );

      }
      //-------------------------------------------------------------- 
      public void test_lists()
      {
         lblTestName.Text = "lists";

         // input parameters
         listsInput input = new listsInput( apikey );
         input.api_AccessType = EnumValues.AccessType.Serial;     //access
         input.api_OutputType = EnumValues.OutputType.JSON;       //output
         input.api_SecureAccess = false;
         input.api_Validate = ValidateRequest;   // validate

         // execution
         lists cmd = new lists( input );
         listsOutput output = cmd.Execute();

         // format output 
         gvOutput.DataSource = output.result; // generic gridview
         gvOutput.DataBind();
         //
         if ( input.api_AccessType == EnumValues.AccessType.XmlRpc )
         { output.api_Request = apiXmlRpcRequestDisplayFormat.FormatParms( output.inputParms ); }

         showResults( output.api_Request, output.api_Response,
            output.api_ErrorMessages, output.api_ValidatorMessages );
      }
      //--------------------------------------------------------------  
      public void test_listBatchSubscribe()
      {
         lblTestName.Text = "listBatchSubscribe";

         // input parameters
         listBatchSubscribeInput input = new listBatchSubscribeInput();
         input.api_AccessType = EnumValues.AccessType.Serial;       // access
         input.api_OutputType = EnumValues.OutputType.JSON;       // output
         input.api_MethodType = MethodType;        // method
         input.api_EncodeRequest = EncodeRequest;  // encode
         input.api_Validate = false;     // validate
         //
         input.parms.apikey = "Your-apikey";

         input.parms.id = "YourListId";

         input.parms.double_optin = false;
         input.parms.replace_interests = MCAPISettings.default_listSubscribe_replace_interests;
         input.parms.update_existing = true;

         // ------------------------------ address
         List<Dictionary<string, object>> batch = new List<Dictionary<string, object>>();
         Dictionary<string, object> entry = new Dictionary<string, object>();
         entry.Add( "EMAIL", "zzz@dbm.com" ); entry.Add( "EMAIL_TYPE", "text" ); entry.Add( "FNAME", "Lidia" );
         entry.Add( "username", "liduser" );
         entry.Add( "homeadr", "215 Lakeside  A  Ajijic  JAL  12345  MX" );
         batch.Add( entry );

         // ------------------------------ address array & date
         entry = new Dictionary<string, object>();
         //
         DateTime dt = DateTime.Now;
         Dictionary<string, object> address = new Dictionary<string, object>();
         address.Add( "addr1", "225 Lakeside" );
         address.Add( "addr2", "A" );
         address.Add( "city", "Ajijic" );
         address.Add( "state", "JAL" );
         address.Add( "zip", "12345" );
         address.Add( "country", "MX" );
         //
         entry.Add( "EMAIL", "xxx@dbm.com" ); entry.Add( "EMAIL_TYPE", "html" ); entry.Add( "FNAME", "David" );
         entry.Add( "mydate", dt );
         entry.Add( "homeadr", address );
         batch.Add( entry );
         // --------------------------------------------- interest groupings
         entry = new Dictionary<string, object>();
         entry.Add( "EMAIL", "yyy@dbm.com" ); entry.Add( "EMAIL_TYPE", "html" ); entry.Add( "FNAME", "Guy" ); entry.Add( "LNAME", "Britain" );
         entry.Add( "username", "gbritain" );
         entry.Add( "homeadr", "409 Monroe Street  Carrolton  NY  14617  US" );
         // ---------------------
         List<interestGroupings> groupings = new List<interestGroupings>();
         //
         interestGroupings ig = new interestGroupings { id = 33, name = "", groups = new List<string> { "dogs, cats" } };
         groupings.Add( ig );
         //
         ig = new interestGroupings();
         ig.id = 0; ig.name = "Work Interests"; ig.groups = new List<string> { "Surveys", "Integration" };
         groupings.Add( ig );
         //
         entry.Add( "groupings", groupings );
         batch.Add( entry );
         // -------------------------
         input.parms.batch = batch;
         //-------------------------------------------------------------- 
         // execution
         listBatchSubscribe cmd = new listBatchSubscribe( input );
         listBatchSubscribeOutput output = cmd.Execute();

         // format output 
         show_listBatch1.Display( output );
         showResults( output.api_Request, output.api_Response,
            output.api_ErrorMessages, output.api_ValidatorMessages );
      }
      //-------------------------------------------------------------- 
      private void test_campaignStats()
      {
         lblTestName.Text = "campaignStats";

         campaignStatsInput input = new campaignStatsInput();
         input.parms.apikey = this.apikey;
         // **** access, output, and validate
         input.api_AccessType = AccessType;
         input.api_OutputType = OutputType;
         input.api_Validate = ValidateRequest;
         //
         input.parms.cid = "yourid";
         // --------------------------------------
         // execution
         campaignStats cmd = new campaignStats( input );
         campaignStatsOutput output = cmd.Execute();

         // format output 
         show_campaignStats1.Display( output );
         showResults( output.api_Request, output.api_Response,
            output.api_ErrorMessages, output.api_ValidatorMessages );
      }
      //---------------------------------------------------------------------- campaignSegmentTest
      public void test_campaignSegmentTest()
      {
         lblTestName.Text = "campaignSegmentTest";

         // input parameters
         campaignSegmentTestInput input = new campaignSegmentTestInput();
         input.parms.apikey = this.apikey;

         input.parms.list_id = "yourlist";    // your list id

         // -------------------------------------------------------------
         campaignSegmentOptions cso = new campaignSegmentOptions();
         cso.match = "any";
         campaignSegmentCondition c1 = new campaignSegmentCondition();
         c1.field = "email"; c1.op = "like"; c1.value = "gmail.com";
         cso.conditions.Add( c1 );
         campaignSegmentCondition c2 = new campaignSegmentCondition();
         c2.field = "email"; c2.op = "like"; c2.value = "yahoo.com";
         cso.conditions.Add( c2 );
         //
         input.parms.options = cso;

         // -------------------------------------------------------------------
         // **** access, output, and validate
         input.api_AccessType = AccessType;
         input.api_OutputType = OutputType;
         input.api_Validate = ValidateRequest;
         // -------------------------------------------------------------------
         // test
         campaignSegmentTest cmd = new campaignSegmentTest( input );
         campaignSegmentTestOutput output = cmd.Execute();

         // format output 
         show_DefaultResponse1.Display( output.result );
         showResults( output.api_Request, output.api_Response,
            output.api_ErrorMessages, output.api_ValidatorMessages );
      }
      //---------------------------------------------------------------------- 
      public void test_campaignEmailDomainPerformance()
      {
         lblTestName.Text = "campaignEmailDomainPerformance";
         campaignEmailDomainPerformanceInput input = new campaignEmailDomainPerformanceInput();
         input.parms.apikey = this.apikey;
         // **** access, output, and validate
         input.api_AccessType = AccessType;
         input.api_OutputType = OutputType;
         input.api_Validate = ValidateRequest;
         //
         input.parms.cid = "your campaign id";
         // --------------------------------------
         // execution
         campaignEmailDomainPerformance cmd = new campaignEmailDomainPerformance( input );
         campaignEmailDomainPerformanceOutput output = cmd.Execute();

         // format output 
         gvOutput.DataSource = output.result;
         gvOutput.DataBind();

         showResults( output.api_Request, output.api_Response,
            output.api_ErrorMessages, output.api_ValidatorMessages );
      }

      //=================================================================================================
      private void showResults( string api_Request, string api_Response,
         List<Api_Error> api_ErrorMessages, List<Api_ValidatorMessage> api_ValidatorMessages )
      {
         if ( showRawRequest ) lblRequest.Text = api_Request;
         if ( showRawResponse ) lblResponse.Text = api_Response;

         show_errors1.Display( api_ErrorMessages, api_ValidatorMessages );
      }

      private void LoadApiMethods()
      {
         methods = ApiHelper.GetApiMethods();
         ddlMethods.DataSource = methods;
         ddlMethods.DataTextField = "title";
         ddlMethods.DataValueField = "name";
         ddlMethods.DataBind();
      }
      private void SetupTest()
      {
         gvOutput.DataSource = ""; gvOutput.DataBind();
         show_DefaultResponse1.Visible = false;
         show_errors1.Visible = false;
         lblRequest.Text = ""; lblResponse.Text = ""; lblTestName.Text = "";
         // -------------------------------- hide user controls -- if any
         show_apikeys1.Visible = false;
         show_listBatch1.Visible = false;
         show_campaignStats1.Visible = false;
         show_listMemberInfo1.Visible = false;
      }
   }
   //
}
